package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"sale_system/goods_srv/global"
	"sale_system/goods_srv/model"
	"sale_system/goods_srv/proto"
)

// 品牌和轮播图接口

func (s *GoodsServer) BrandList(ctx context.Context, request *proto.BrandFilterRequest) (*proto.BrandListResponse, error) {

	// 从数据库读取数据到切片
	var brands []model.Brands

	result := global.DB.Scopes(Paginate(int(request.Pages), int(request.PagePerNums))).Find(&brands)

	if result.Error != nil {
		return nil, result.Error
	}

	var total int64
	rsp := &proto.BrandListResponse{}
	global.DB.Model(&model.Brands{}).Count(&total)

	rsp.Total = int32(total)

	// brand就是一个切片数据
	for _, brand := range brands {
		// 构造一个brandInfo结构体，读取从获得的一个切片数据
		brandInfo := &proto.BrandInfoResponse{
			Name: brand.Name,
			Id:   brand.ID,
			Logo: brand.Logo,
		}
		rsp.Data = append(rsp.Data, brandInfo)
	}

	return rsp, nil
}

func (s *GoodsServer) CreateBrand(ctx context.Context, request *proto.BrandRequest) (*proto.BrandInfoResponse, error) {

	// 品牌不能重名，先在数据库进行判断
	result := global.DB.First(&model.Brands{}, request.Name)
	if result.RowsAffected != 0 {
		return nil, status.Error(codes.AlreadyExists, result.Error.Error()) // 品牌已经存在
	}

	brand := &model.Brands{
		Name: request.Name,
		Logo: request.Logo,
	}
	// 将这个品牌添加到数据库中
	global.DB.Save(brand)

	return &proto.BrandInfoResponse{Id: brand.ID}, nil
}

func (s *GoodsServer) DeleteBrand(ctx context.Context, request *proto.BrandRequest) (*emptypb.Empty, error) {

	result := global.DB.First(&model.Brands{}, request.Id)
	if result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "品牌不存在") // 品牌不存在
	}
	// 删除一定要存在
	_ = global.DB.Delete(&model.Brands{}, request.Id)

	return &emptypb.Empty{}, nil
}
func (s *GoodsServer) UpdateBrand(ctx context.Context, request *proto.BrandRequest) (*emptypb.Empty, error) {
	// 品牌不能不存在
	brand := model.Brands{}
	result := global.DB.First(&brand, request.Id)
	if result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, result.Error.Error()) // 品牌不存在
	}

	// 查看是否为空
	if request.Name != "" {
		brand.Name = request.Name
	}
	if request.Logo != "" {
		brand.Logo = request.Logo
	}

	// 将这个品牌添加到数据库中
	global.DB.Save(&brand)

	return &emptypb.Empty{}, nil
}
